package com.example.dzl.controller;

import com.example.dzl.request.RefreshTokenRequest;
import com.example.dzl.response.TokenResponse;
import com.example.dzl.util.JwtTokenUtil;
import com.example.dzl.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class TestController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @GetMapping("/public/info")
    public Result publicInfo() {
        Map<String, Object> data = new HashMap<>();
        data.put("message", "这是一个公开API，无需认证");
        data.put("timestamp", System.currentTimeMillis());
        return Result.success(data);
    }

    @PostMapping("/public/refresh")
    public Result refreshToken(@RequestBody RefreshTokenRequest request) {

        String refreshToken = request.getRefreshToken();

        if (jwtTokenUtil.validateToken(refreshToken) && !jwtTokenUtil.isTokenExpired(refreshToken)) {
            String username = jwtTokenUtil.getUsernameFromToken(refreshToken);
            String newAccessToken = jwtTokenUtil.generateAccessToken(username);
            String newRefreshToken = jwtTokenUtil.generateRefreshToken(username);

            TokenResponse tokenResponse = new TokenResponse(newAccessToken, newRefreshToken, 3600L);
            return Result.success(tokenResponse);
        } else {

            return Result.error(HttpStatus.UNAUTHORIZED.value(), "Refresh Token无效或已过期");
        }
    }

    @GetMapping("/protected/resource")
    public Result protectedResource() {
        Map<String, Object> data = new HashMap<>();
        data.put("message", "这是一个受保护的API，需要有效的Access Token");
        data.put("secretData", "这是敏感数据，只有认证用户才能访问");
        data.put("timestamp", System.currentTimeMillis());
        return Result.success(data);
    }
    @GetMapping("/protected/user-info")
    public Result userInfo() {
        Map<String, Object> data = new HashMap<>();
        data.put("message", "这是用户信息");
        data.put("timestamp", System.currentTimeMillis());
        return Result.success(data);
    }
}